package com.zc.websocket.handler.event;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.zc.common.constant.RedisStreamConstants;
import com.zc.common.core.redis.stream.RedisStream;
import com.zc.common.core.websocket.pojo.RedisWebSocketMsg;
import com.zc.websocket.bo.ChannelProperty;
import com.zc.websocket.bo.ChannelPropertyCommon;
import com.zc.websocket.constant.AttributeKeyConst;
import com.zc.websocket.core.TextWebSocketFrameHandler;
import com.zc.websocket.dto.param.EventParam;
import com.zc.websocket.dto.param.LoginParam;
import com.zc.websocket.dto.result.CmdExeResult;
import com.zc.websocket.dto.result.CmdMsg;
import com.zc.websocket.dto.result.JsonMsg;
import com.zc.websocket.enums.ChannelStatus;
import com.zc.websocket.enums.ErrorCodeEnum;
import com.zc.websocket.handler.CmdHandler;
import org.apache.poi.ss.formula.functions.T;

import java.lang.reflect.Type;
import java.util.logging.Logger;

/**
 * 消息的处理器
 * @author Athena-xiepufeng
 */
public class EventCmdHandler implements CmdHandler
{

    private static final Logger log = Logger.getLogger(EventCmdHandler.class.getName());

    private final RedisStream redisStream = SpringUtils.getBean(RedisStream.class);

    /*
     * 消息通道处理器
     */
    private TextWebSocketFrameHandler channelHandler;

    @Override
    public CmdExeResult execute(JsonMsg jsonMsg)
    {
        @SuppressWarnings("unchecked")
        CmdMsg<EventParam<String>> cmdMsg = (CmdMsg<EventParam<String>>) jsonMsg;

        CmdExeResult result = new CmdExeResult();

        result.setJsonMsg(jsonMsg);

        ChannelProperty channelProperty = channelHandler.getCtx().channel().attr(AttributeKeyConst.CHANNEL_PROPERTY_KEY).get();

        // 检测是否绑定 tokenSN
        if (!ChannelStatus.TOKENSN_BOUND.equals(channelProperty.getStatus()))
        {
            result.setCode(ErrorCodeEnum.ERR_UNAUTHORIZED.getInternalCode());
            result.setMessage(ErrorCodeEnum.ERR_UNAUTHORIZED.getInternalMessage());
            log.warning("检测未绑定到 tokenSN！");
            return result;
        }

        result.setCode(ErrorCodeEnum.ERR_OK.getInternalCode());
        result.setMessage(ErrorCodeEnum.ERR_OK.getInternalMessage());

        EventParam<String> eventParam = cmdMsg.getParams();
        eventParam.setTokenSN(channelProperty.getTokenSN());

        Gson gson = new Gson();
        Type type = new TypeToken<EventParam<String>>()
        {
        }.getType();

        String msg = gson.toJson(eventParam, type);

        redisStream.add(RedisStreamConstants.WebSocketStreamEvent.KEY, "", msg);

        return result;

    }

    public TextWebSocketFrameHandler getChannelHandler()
    {
        return channelHandler;
    }

    public void setChannelHandler(TextWebSocketFrameHandler channelHandler)
    {
        this.channelHandler = channelHandler;
    }

}
